<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>2-ajax复杂封装</title>
</head>

<body>
  <button id="btn">发送GET请求</button>
  <button id="btn2">发送POST请求</button>

  <ul></ul>

  <script src="./axios.js"></script>
  <script>
    document.getElementById('btn').onclick = () => {
      axios({ // 配置对象: 属性名是一些特定的名称
        method: 'GET',
        url: 'http://localhost:8081/prodcuts/A', // 携带了params参数
        params: { price: 20 }, // 指定query参数
      }).then(
        (response) => {
          // console.log(response)
          const lis = response.data.reduce(
            (pre, p) => `${pre}<li>${p.id}--${p.name}--${p.price}</li>`,
            ''
          );
          document.querySelector('ul').innerHTML = lis;
        },
        (error) => {
          alert(error.message);
        }
      );
    };

    document.getElementById('btn2').onclick = () => {
      axios({
        method: 'POST',
        url: 'http://localhost:8081/prodcuts/add',
        data: { name: 'C1', price: 40 }, // body参数
      }).then(
        (response) => {
          const lis = response.data.reduce(
            (pre, p) => `${pre}<li>${p.id}--${p.name}--${p.price}</li>`,
            ''
          );
          document.querySelector('ul').innerHTML = lis;
        },
        (error) => {
          alert(error.message);
        }
      );
    };
  </script>
</body>

</html>